<template>
  <view class="coupon-merge-page">
    <!-- 导航栏 -->
    <NavBar title="优惠券合成" />

    <!-- 合成说明 -->
    <view class="merge-intro">
      <view class="intro-title">优惠券合成</view>
      <view class="intro-desc">将多张小额优惠券合成一张大额优惠券，提升优惠力度！</view>
    </view>

    <!-- 合成区域 -->
    <view class="merge-area">
      <view class="merge-title">选择要合成的优惠券</view>
      
      <!-- 选择的优惠券列表 -->
      <view class="selected-coupons">
        <view 
          v-for="(item, index) in selectedCoupons" 
          :key="index"
          class="coupon-item"
          @click="removeCoupon(index)"
        >
          <view class="coupon-amount">¥{{ item.amount }}</view>
          <view class="remove-icon">
            <Close size="12" />
          </view>
        </view>
        
        <!-- 添加按钮 -->
        <view class="add-coupon" @click="showCouponSelector = true" v-if="selectedCoupons.length < 3">
          <Plus size="20" />
        </view>
      </view>

      <!-- 合成结果预览 -->
      <view class="merge-result" v-if="selectedCoupons.length > 0">
        <view class="result-title">合成后的优惠券</view>
        <view class="result-coupon">
          <view class="coupon-left">
            <view class="coupon-amount">
              <text class="symbol">¥</text>
              <text class="value">{{ mergedAmount }}</text>
            </view>
            <view class="coupon-condition">满{{ mergedMinAmount }}元可用</view>
          </view>
          <view class="coupon-right">
            <view class="coupon-name">合成优惠券</view>
            <view class="coupon-scope">全场通用</view>
            <view class="coupon-time">有效期：{{ validTimeDesc }}</view>
          </view>
        </view>
      </view>

      <!-- 合成按钮 -->
      <view class="merge-action">
        <nut-button 
          type="primary" 
          block 
          :disabled="selectedCoupons.length < 2" 
          @click="mergeCoupons"
          :loading="merging"
        >
          {{ selectedCoupons.length < 2 ? '请选择至少2张优惠券' : '立即合成' }}
        </nut-button>
      </view>
    </view>

    <!-- 合成规则 -->
    <view class="merge-rules">
      <view class="rules-title">合成规则</view>
      <view class="rules-content">
        <view class="rule-item">1. 每次最多可选择3张优惠券进行合成</view>
        <view class="rule-item">2. 只能合成未使用且未过期的优惠券</view>
        <view class="rule-item">3. 合成后的优惠券金额为所选优惠券金额的85%之和</view>
        <view class="rule-item">4. 合成后原优惠券将作废，不可恢复</view>
        <view class="rule-item">5. 合成后的优惠券有效期为30天</view>
      </view>
    </view>

    <!-- 优惠券选择弹窗 -->
    <nut-popup position="bottom" v-model:visible="showCouponSelector">
      <view class="coupon-selector">
        <view class="selector-header">
          <view class="selector-title">选择优惠券</view>
          <view class="selector-close" @click="showCouponSelector = false">
            <Close />
          </view>
        </view>
        <view class="selector-content">
          <!-- 空优惠券提示 -->
          <nut-empty v-if="availableCoupons.length === 0" description="暂无可用优惠券" image="empty">
            <template #footer>
              <nut-button type="primary" size="small" @click="goCouponCenter">去领券</nut-button>
            </template>
          </nut-empty>

          <!-- 可选优惠券列表 -->
          <view v-else class="coupon-list">
            <view 
              v-for="(item, index) in availableCoupons" 
              :key="index"
              class="coupon-item"
              :class="{ 'disabled': isSelected(item) }"
              @click="selectCoupon(item)"
            >
              <view class="coupon-left">
                <view class="coupon-amount">
                  <text class="symbol">¥</text>
                  <text class="value">{{ item.amount }}</text>
                </view>
                <view class="coupon-condition">满{{ item.minAmount }}元可用</view>
              </view>
              <view class="coupon-right">
                <view class="coupon-name">{{ item.name }}</view>
                <view class="coupon-scope">{{ item.scope }}</view>
                <view class="coupon-time">{{ item.validTimeDesc }}</view>
                <view class="coupon-select" v-if="isSelected(item)">
                  <Checked color="#fa2c19" size="16" />
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="selector-footer">
          <nut-button type="primary" block @click="confirmSelection">确认选择</nut-button>
        </view>
      </view>
    </nut-popup>

    <!-- 合成成功弹窗 -->
    <nut-popup v-model:visible="showSuccessPopup" :style="{ padding: '30px 50px' }">
      <view class="success-popup">
        <view class="success-icon">
          <Success size="40" color="#fa2c19" />
        </view>
        <view class="success-title">合成成功</view>
        <view class="success-desc">已成功合成一张{{ mergedAmount }}元优惠券</view>
        <view class="success-buttons">
          <nut-button type="primary" @click="goToCouponList">查看我的优惠券</nut-button>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import NavBar from '@/components/NavBar/index.vue'
import userApi from '@/api/user'
import type { Coupon } from '@/types/http'
import { useLoading } from '@/hooks/useLoading'
import { Close, Plus, Checked, Success } from '@nutui/icons-vue-taro'

// 选中的优惠券
const selectedCoupons = ref<Coupon[]>([])

// 可用于合成的优惠券列表
const availableCoupons = ref<Coupon[]>([])

// 弹窗显示状态
const showCouponSelector = ref(false)
const showSuccessPopup = ref(false)

// 合成状态
const merging = ref(false)

// 加载状态
const { loading, showLoading, hideLoading } = useLoading()

// 合成后的优惠券金额
const mergedAmount = computed(() => {
  if (selectedCoupons.value.length === 0) return 0
  
  // 计算所有选中优惠券金额的85%之和
  const total = selectedCoupons.value.reduce((sum, coupon) => {
    return sum + Number(coupon.amount) * 0.85
  }, 0)
  
  // 四舍五入到整数
  return Math.round(total)
})

// 合成后的优惠券使用门槛
const mergedMinAmount = computed(() => {
  if (selectedCoupons.value.length === 0) return 0
  
  // 计算所有选中优惠券使用门槛的平均值
  const total = selectedCoupons.value.reduce((sum, coupon) => {
    return sum + Number(coupon.minAmount)
  }, 0)
  
  // 向上取整到十位
  return Math.ceil(total / selectedCoupons.value.length / 10) * 10
})

// 有效期描述
const validTimeDesc = computed(() => {
  const now = new Date()
  const end = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000) // 30天后
  
  const formatDate = (date: Date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
  
  return `${formatDate(now)} ~ ${formatDate(end)}`
})

// 获取可用于合成的优惠券列表
const getAvailableCoupons = async () => {
  try {
    showLoading('加载中...')
    
    const res = await userApi.getMergeableCoupons()
    
    if (res && res.data) {
      availableCoupons.value = res.data
    } else {
      availableCoupons.value = []
    }
    
  } catch (error) {
    console.error('获取可用优惠券列表失败', error)
    Taro.showToast({
      title: '获取优惠券列表失败',
      icon: 'none'
    })
  } finally {
    hideLoading()
  }
}

// 判断优惠券是否已被选中
const isSelected = (coupon: Coupon) => {
  return selectedCoupons.value.some(item => item.id === coupon.id)
}

// 选择优惠券
const selectCoupon = (coupon: Coupon) => {
  // 如果已经选中，则取消选择
  if (isSelected(coupon)) {
    const index = selectedCoupons.value.findIndex(item => item.id === coupon.id)
    if (index !== -1) {
      selectedCoupons.value.splice(index, 1)
    }
    return
  }
  
  // 如果已经选择了3张，则不能再选
  if (selectedCoupons.value.length >= 3) {
    Taro.showToast({
      title: '最多只能选择3张优惠券',
      icon: 'none'
    })
    return
  }
  
  // 添加到已选列表
  selectedCoupons.value.push(coupon)
}

// 移除已选优惠券
const removeCoupon = (index: number) => {
  selectedCoupons.value.splice(index, 1)
}

// 确认选择
const confirmSelection = () => {
  showCouponSelector.value = false
}

// 合成优惠券
const mergeCoupons = async () => {
  if (selectedCoupons.value.length < 2) return
  
  try {
    merging.value = true
    
    const couponIds = selectedCoupons.value.map(coupon => coupon.id)
    const res = await userApi.mergeCoupons(couponIds)
    
    if (res.code === 0) {
      showSuccessPopup.value = true
      selectedCoupons.value = []
      await getAvailableCoupons()
      // 更新store中的优惠券列表
      useUserStore().updateCoupons(res.data.newCoupon)
    }
    
  } catch (error) {
    console.error('合成优惠券失败', error)
    Taro.showToast({
      title: '合成失败，请稍后再试',
      icon: 'none'
    })
  } finally {
    merging.value = false
  }
}

// 去领券中心
const goCouponCenter = () => {
  Taro.navigateTo({
    url: '/pages/coupon/center'
  })
}

// 查看我的优惠券
const goToCouponList = () => {
  showSuccessPopup.value = false
  Taro.navigateTo({
    url: '/pages/coupon/index'
  })
}

// 页面加载时获取可用优惠券
onMounted(() => {
  getAvailableCoupons()
})
</script>

<style lang="scss">
.coupon-merge-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 30px;
  
  .merge-intro {
    background-color: #fff;
    padding: 20px 16px;
    margin-bottom: 10px;
    
    .intro-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 8px;
      color: #333;
    }
    
    .intro-desc {
      font-size: 14px;
      color: #666;
    }
  }
  
  .merge-area {
    background-color: #fff;
    padding: 20px 16px;
    margin-bottom: 10px;
    
    .merge-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
    }
    
    .selected-coupons {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-bottom: 20px;
      
      .coupon-item {
        position: relative;
        width: 100px;
        height: 100px;
        background: linear-gradient(135deg, #ff6b6b, #fa2c19);
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #fff;
        
        .coupon-amount {
          font-size: 24px;
          font-weight: bold;
        }
        
        .remove-icon {
          position: absolute;
          top: 5px;
          right: 5px;
          width: 18px;
          height: 18px;
          background-color: rgba(0, 0, 0, 0.3);
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
      
      .add-coupon {
        width: 100px;
        height: 100px;
        border: 1px dashed #ccc;
        border-radius: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #999;
      }
    }
    
    .merge-result {
      margin-bottom: 20px;
      
      .result-title {
        font-size: 16px;
        margin-bottom: 10px;
        color: #333;
      }
      
      .result-coupon {
        display: flex;
        height: 90px;
        background: linear-gradient(135deg, #ff9a9e, #fa2c19);
        border-radius: 8px;
        overflow: hidden;
        position: relative;
        
        .coupon-left {
          width: 120px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          color: #fff;
          position: relative;
          
          &::after {
            content: '';
            position: absolute;
            right: 0;
            top: 0;
            bottom: 0;
            border-right: 1px dashed rgba(255, 255, 255, 0.3);
          }
          
          .coupon-amount {
            display: flex;
            align-items: baseline;
            
            .symbol {
              font-size: 16px;
              margin-right: 2px;
            }
            
            .value {
              font-size: 28px;
              font-weight: bold;
            }
          }
          
          .coupon-condition {
            font-size: 12px;
            margin-top: 5px;
          }
        }
        
        .coupon-right {
          flex: 1;
          padding: 15px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          color: #fff;
          
          .coupon-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 5px;
          }
          
          .coupon-scope {
            font-size: 12px;
            margin-bottom: 5px;
          }
          
          .coupon-time {
            font-size: 12px;
          }
        }
      }
    }
  }
  
  .merge-rules {
    background-color: #fff;
    padding: 20px 16px;
    
    .rules-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
    }
    
    .rules-content {
      .rule-item {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
        line-height: 1.5;
      }
    }
  }
  
  .coupon-selector {
    height: 70vh;
    display: flex;
    flex-direction: column;
    
    .selector-header {
      padding: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #eee;
      
      .selector-title {
        font-size: 16px;
        font-weight: bold;
      }
    }
    
    .selector-content {
      flex: 1;
      overflow-y: auto;
      padding: 15px;
      
      .coupon-list {
        .coupon-item {
          display: flex;
          height: 90px;
          background-color: #fff;
          border-radius: 8px;
          overflow: hidden;
          position: relative;
          margin-bottom: 15px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          
          &.disabled {
            opacity: 0.6;
          }
          
          .coupon-left {
            width: 120px;
            background: linear-gradient(135deg, #ff6b6b, #fa2c19);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: #fff;
            position: relative;
            
            &::after {
              content: '';
              position: absolute;
              right: 0;
              top: 0;
              bottom: 0;
              border-right: 1px dashed rgba(255, 255, 255, 0.3);
            }
            
            .coupon-amount {
              display: flex;
              align-items: baseline;
              
              .symbol {
                font-size: 16px;
                margin-right: 2px;
              }
              
              .value {
                font-size: 24px;
                font-weight: bold;
              }
            }
            
            .coupon-condition {
              font-size: 12px;
              margin-top: 5px;
            }
          }
          
          .coupon-right {
            flex: 1;
            padding: 15px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            
            .coupon-name {
              font-size: 16px;
              font-weight: bold;
              margin-bottom: 5px;
              color: #333;
            }
            
            .coupon-scope {
              font-size: 12px;
              color: #666;
              margin-bottom: 5px;
            }
            
            .coupon-time {
              font-size: 12px;
              color: #999;
            }
            
            .coupon-select {
              position: absolute;
              right: 15px;
              top: 15px;
            }
          }
        }
      }
    }
    
    .selector-footer {
      padding: 15px;
      border-top: 1px solid #eee;
    }
  }
  
  .success-popup {
    text-align: center;
    
    .success-icon {
      margin-bottom: 15px;
    }
    
    .success-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #333;
    }
    
    .success-desc {
      font-size: 14px;
      color: #666;
      margin-bottom: 20px;
    }
  }
}
</style>